package cn.gson.querydsl.dao;

import jakarta.persistence.Table;
import org.hibernate.query.TupleTransformer;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>****************************************************************************</p>
 * <ul style="margin:15px;">
 * <li>Description : </li>
 * <li>Version     : 1.0</li>
 * <li>Creation    : 2024年07月19日</li>
 * <li>@author     : ____′↘夏悸</li>
 * </ul>
 * <p>****************************************************************************</p>
 */
public class OneResultTransformer implements TupleTransformer {
    private Class<?> returnType;

    public OneResultTransformer(Class<?> returnType) {
        this.returnType = returnType;
    }

    @Override
    public Object transformTuple(Object[] tuple, String[] aliases) {
        if (returnType == Map.class) {
            Map<String, Object> map = new HashMap<>();
            if (tuple.length == 1 && tuple[0].getClass().isAnnotationPresent(Table.class)) {
                copy(tuple[0], map);
            } else {
                for (int i = 0; i < aliases.length; i++) {
                    map.put(aliases[i], tuple[i]);
                }
            }
            return map;
        }
        if (tuple.length > 1)
            throw new IllegalArgumentException("返回结果有多个列，接收类型：" + returnType.getName());
        return tuple[0];
    }

    protected void copy(Object source, Map tag) {
        for (Field field : source.getClass().getDeclaredFields()) {
            Object o = null;
            try {
                field.setAccessible(true);
                o = field.get(source);
                tag.put(field.getName(), o);
            } catch (IllegalAccessException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
